package cn.yzj.utils;

import cn.yzj.entity.AliOssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;

import java.util.Objects;

/**
 * 阿里云 OSS 工具类
 *
 * @author gzkemays
 * @since 2021/2/9 22:16
 */
@Data
public class AliUtils {

  /**
   * 上传图片至 OSS 服务
   *
   * @param config oss 服务配置对象
   * @return 上传回调的地址
   */
  public static String uploadImgToOSS(AliOssConfig config) {
    String endPoint = config.getEndPoint();
    String accessKey = config.getAccessKey();
    String security = config.getSecretKey();
    String savePath =
        config.getSavePath().endsWith("/") ? config.getSavePath() : config.getSavePath() + "/";
    String bucketName = config.getBucketName();
    String ext = Objects.isNull(config.getExt()) ? "" : config.getExt();
    OSS ossClient = new OSSClient(endPoint, accessKey, security);
    String fileName;
    if (Objects.isNull(config.getFileName())) {
      fileName = savePath + System.currentTimeMillis() + ext;
    } else {
      fileName = savePath + config.getFileName() + ext;
    }
    ossClient.putObject(bucketName, fileName, config.getStream());
    ossClient.shutdown();
    return fileName;
  }
}
